# -*- coding: UTF-8 -*-
# @Time : 2022/1/5 0005 14:31
# @Author : lyw
# @Remark :
import logging
import re

from mxsoftpy.exception import DBError

from db.public.IOTManager.iot_base import IOTBaseDB
from index import mini_cache, _
from utils.classes.custom_exception import VerifyError


class PowerDeviceSelectDB(IOTBaseDB):
    device_type = "Power"
    query_field = ["mxlabel", "mxdevicetype", "mxparent", "isdel"]

    def read_template(self):
        """
        读取设备模板
        @return:
        """
        db_path = "EntityTemplate"
        ups_temp_dict = {}
        ups_temp_cache = mini_cache.get("POWER_TEMP_CACHE")
        if ups_temp_cache:
            logging.info("power 模板读取缓存")

            return mini_cache["POWER_TEMP_CACHE"]
        for monitor_sub_code in self.tree.open(db_path, "IOT\\Power", file="base").sub_keys():
            # for monitor_sub_code in ['Lhasa_ElectricityMeter']:
            sub_path = "\\".join(["IOT", "Power", monitor_sub_code, "MonitorEx"])
            plugin_dict = {"in": [], "out": [], "property": []}

            for monitor_key in self.tree.open(db_path, sub_path, file="base").sub_keys():
                monitor_value = self.tree.open(db_path, "\\".join([sub_path, monitor_key]), file="base").items()
                self.query_run_mode(monitor_value["mxpluginname"], plugin_dict)

            else:
                if plugin_dict:
                    ups_temp_dict[monitor_sub_code] = plugin_dict
        mini_cache.set("POWER_TEMP_CACHE", ups_temp_dict, 24 * 60 * 60)
        logging.info("power 模板设置了缓存")
        return ups_temp_dict

    def regular_monitor(self, search_list, value):
        """
        匹配 字符
        @param search_list:
        @param value:
        @return:
        """
        not_re = "线|旁路|交流屏"
        for search_dict in search_list:
            if re.search(search_dict["name"], value):
                if search_dict["name"] == "电压":
                    if re.search(not_re, value):
                        return None
                    else:
                        return search_dict['key']
                elif search_dict["name"] == "电流":
                    if re.search(not_re, value):
                        return None
                    else:
                        return search_dict['key']
                if search_dict.get("child"):
                    regular_res = self.regular_monitor(search_dict["child"], value)
                    if regular_res:
                        return regular_res

    def query_run_mode(self, mxpluginname, plugin_dict: dict):
        """
        获取 plugin 数据
        @param plugin_dict:
        @param mxpluginname:
        @return:
        """

        path = "PluginData"
        monitor_dict = {"child": []}
        try:
            for out_sub in self.tree.open(path, mxpluginname + "\\Output", file="base").sub_keys():
                plugin_data = self.tree.open(path, mxpluginname + "\\Output\\%s" % out_sub, file="base").items(
                    ["mxlabel", "mxunit"])

                search_data = [{"name": "主路|进线|输入|A|B|C",
                                "child": [{"name": "电压", "key": "in"}]},
                               {"name": "输出|A|B|C",
                                "child": [{"name": "电流", "key": "out"}]}]
                plugin_key = self.regular_monitor(search_list=search_data, value=plugin_data["mxlabel"])
                plugin_data["code"] = out_sub
                plugin_data["name"] = mxpluginname
                if plugin_key:
                    if plugin_data["mxunit"] in ("V", "A"):
                        plugin_dict[plugin_key].append(plugin_data)

                monitor_dict["label"] = self.tree.open(path, mxpluginname, file="base").fetchone_value("mxlabel")
                monitor_dict["name"] = mxpluginname
                monitor_dict["child"].append(plugin_data)
            plugin_dict["property"].append(monitor_dict)
        except DBError as e:
            logging.error(e)

    def get_sub_monitor(self, code, device_data):
        """
        获取设备的监测点信息
        @param dev_code:
        @return:
        """

        monitor_res_dict = {}
        try:
            ups_sub_list = self.tree.open("MXSE", "1\\1.SD\\%s\\%s.SubMonitor" % (code, code),
                                          file="ccubase").sub_keys()
            for ups_sub_key in ups_sub_list:
                ups_sub_monitor = self.tree.open("MXSE",
                                                 "1\\1.SD\\%s\\%s.SubMonitor\\%s" % (code, code, ups_sub_key),
                                                 file="ccubase").items(prop_list="mxpluginname")

                monitor_res_dict[ups_sub_key] = ups_sub_monitor["mxpluginname"]
        except DBError as e:
            logging.error(e)

        device_data["sub_monitor"] = monitor_res_dict

    def param_middle(self, data_obj) -> dict:
        """
        基础查询 参数
        @param data_obj:
        @return:
        """
        return {"iot_code": data_obj.iot_code, "device_type": data_obj.device_type}

class PowerDeviceListDB(PowerDeviceSelectDB):
    def get_sub_monitor(self, code, device_data):
        pass


class PowerDeviceRetrieveDB(PowerDeviceSelectDB):

    def select(self, **kwargs):
        """
        获取设备
        @return:
        """
        query_field = ["mxlabel", "mxdevicetype", "mxparent"]
        try:

            dev_value = self.tree.open("MXSE", "1\\1.SD\\%s" % kwargs["code"], file="ccubase").items(query_field)

            self.get_sub_monitor(kwargs["code"], dev_value)
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询设备错误"))
        return dev_value
